<?php
// 活动控制器
class Controller_WWW_Activity extends Controller_WWW_Template
{
    public function __construct ($req, $res)
    {
        $this->template = "smarty:www/activity";
        parent::__construct($req, $res);
    }

    public function action_index ($page = 1)
    {
        $activity = new App_Activity();
        $page     = max(1, $page);
        $limit    = 6;
        $offset   = $limit * ($page - 1);
        list($counts,$list) = $activity->search(NULL,$offset,$limit);
        $pagination = $this->pagination($counts, $limit, $page_type = 'route', $page_key = 'param1', $views = 'www/page/new');
        $this->template->set('pagination', $pagination);
        
        $countrys=App_Config::optionsCountryList();
        $citys=App_Config::optionsCityList();
        foreach($countrys as &$cou){
        	$cou=array("val"=>$cou,"selected"=>1);
        }
        foreach($citys as &$cit){
        	$cit=array("val"=>$cit,"selected"=>1);
        }
        $this->template->set('countrys',$countrys);
        $this->template->set('scitys',$citys);        

        $this->template->set('list', $list);
        $this->template->set('counts', $counts);
        $this->template->set('step', 'activity');
    }

    //活动查找
    public function action_search($page = 1){
        $query = $this->request->query();

        $scity = Arr::get($query,'city');
        $scountry = Arr::get($query,'country');
        $start = Arr::get($query,'start');
        $end = Arr::get($query,'end');
        $TouristCounts = Arr::get($query,'number');
        $fabu = Arr::get($query,'fabu');
        $age = Arr::get($query,'age');
        $gender = Arr::get($query,'gender');
        $identity = Arr::get($query,'identity');
        $language = Arr::get($query,'language');
        $chuxing = Arr::get($query,'chuxing');
        $price = Arr::get($query,'price');
        $orders = Arr::get($query,'orders');
        $score = Arr::get($query,'score');
        $people = Arr::get($query,'people_num');

        $page     = max(1, $page);
        $limit    = 6;
        $offset   = $limit * ($page - 1);

        list($counts,$tracks) = App_Activity_Search::getActivity($scity,$scountry,$start,$end,$TouristCounts,$fabu,
            $age,$gender,$identity,$language,$chuxing,$people,$price,$orders,$score,
            $limit,$offset
            );

        $pagination = $this->pagination($counts, $limit, $page_type = 'route', $page_key = 'param1', $views = 'www/page/new');
        $this->template->set('pagination', $pagination);
//        var_dump($counts,$tracks);
        //$this->template->set('country',$country);
        $countrys=App_Config::optionsCountryList();
        if($scountry===-1){
        	$citys=App_Config::optionsCityList();
        }else{
        	$citys=App_Config::optionsCityListByCountry($scountry);
        }
        foreach($countrys as &$cou){
        	if($cou==$scountry)
        	{$cou=array("val"=>$cou,"selected"=>2);}
        	else{$cou=array("val"=>$cou,"selected"=>1);}
        }
        foreach($citys as &$cit){
        	if($cit==$scity)
        	{$cit=array("val"=>$cit,"selected"=>2);}
        	else{$cit=array("val"=>$cit,"selected"=>1);}
        }
        $this->template->set('countrys',$countrys);
        $this->template->set('scitys',$citys);
        
        $this->template->set('counts',$counts);
        $this->template->set('list',$tracks);
        $this->template->set('fabu',$fabu);
        $this->template->set('age',$age);
        $this->template->set('gender',$gender);
        $this->template->set('identity',$identity);
        $this->template->set('language',$language);
        $this->template->set('chuxing',$chuxing);
        //$this->template->set('scity',$city);
        $this->template->set('start',$start);
        $this->template->set('end',$end);
        $this->template->set('number',$TouristCounts);
        $this->template->set('step','track');
        $this->template->set('people_num',$people);
        $this->template->set('price',$price);
        $this->template->set('orders',$orders);
        $this->template->set('score',$score);
        $this->template->set_filename('smarty:www/activity_search');
        $this->template->set('step', 'activity');
    }

    // 分类下的活动
    public function action_category ($catId, $page = 1)
    {
        $activity = new App_Activity();
        $page     = max(1, $page);
        $limit    = 10;
        $offset   = $limit * ($page - 1);
        list($counts,$list) = $activity->listByCategory($catId,$offset,$limit, $catId);
        $pagination = $this->pagination($counts, $limit);
        $this->template->set('pagination', $pagination);
        $this->template->set('list', $list);
        $this->template->set('counts', $counts);
        $this->template->set('step', 'activity');
    }

    // 活动详情
    public function action_detail ($activityId)
    {
        $activity  = new App_Activity($activityId);
        $detail = $activity->detail();

        $comments = Comments::getActivityOrTrackComments($activityId,"activity",5,0);
        foreach($comments as &$v){
            $v['tourist_pic'] = explode(';',$v['tourist_pic']);
        }
        $this->template->set("comments",$comments);

        $order     = new Order;
        // 暂时屏蔽
        // $orderDays = $order->getActivityOrderDays($activityId);
        // $this->template->set('orderDays', $orderDays);

        // 导游空闲时间
        $this->template->set('guiderFreeDays', $activity->getCurrentGuiderFreeDays());

//        $srvMaxPersons = Arr::get($detail, 'serviceMaxPersons');
//        $orderPersons  = $order->getActivityOrderPersons($activityId);
//        $leftPersons   = $srvMaxPersons - $orderPersons;
//        $leftPersons   = $leftPersons > 0 ? $leftPersons : 0;
//        $this->template->set('srvLeftPersons', $leftPersons);

        $this->template->set_filename('smarty:www/activity/activity_detail');
        $this->template->set('activity', $detail);
        $this->template->set('counts', count($comments));
        $this->template->set('step', 'activity');

        $maxPersons = Arr::get($detail, 'serviceMaxPersons', 0);
        $n = 1;
        $persons    = array();
        while ($n <= $maxPersons && $n <= 15)
        {
            $persons[] = $n;
            $n+= 1;
        }
        $this->template->set('personList', $persons);
 
    }

    //获取更多评论
    public function action_get_more($page = 2){
        $query = $this->request->query();
        $activityId = Arr::get($query,'id');
        $page   = max($page, 1);
        $limit  = 5;
        $offset = ($page - 1) * $limit;
        $comments = Comments::getActivityOrTrackComments($activityId,"activity",$limit,$offset);
        foreach($comments as &$v){
            $v['tourist_pic'] = explode(';',$v['tourist_pic']);
        }
        $this->template->set_filename('smarty:www/activity/item');
        $this->template->set('comments',$comments);
        $rs = $this->template->render();

        echo $rs;
        exit;
    }


    // 创建
    public function action_create ()
    {
        $this->request->redirect('/activity/create_basic');
    }

    // 删除
    public function action_remove ($activityId)
    {
        $activity = new App_Activity($activityId);
        $detail = $activity->detail();
        $uid    = Arr::get($detail, 'uid');
        if ($uid > 0 && $uid == $this->_uid)
        {
            $activity->remove();
        }

        $referrer = $this->request->referrer();
        $this->request->redirect($referrer);
    }



    public function action_create_basic ($activityId = NULL)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $cityList=App_City::getCityListCn();
            $this->template->set('cityList',$cityList);
            $this->template->set_filename('smarty:www/activity/create');

            if ($activityId > 0)
            {
              $activity = new App_Activity($activityId);
              $act_data=$activity->detail();
              $this->template->set('activity', $act_data);
            }
        }
        else
        {
            $uid    = $this->_uid;
            $srv70s = (int) Arr::get($post, 'support70s', 0);
            $srv80s = (int) Arr::get($post, 'support80s', 0);
            $srv90s = (int) Arr::get($post, 'support90s', 0);
            $srv00s = (int) Arr::get($post, 'support00s', 0);

            $srvMin = (int) Arr::get($post, 'serviceMinPersons', 0);
            $srvMax = (int) Arr::get($post, 'serviceMaxPersons', 0);

            $city   = trim(Arr::get($post, 'city'));
            $cityId = (int)Arr::get($post, 'cityId');
            $country= trim(Arr::get($post, 'country'));
            $locName= trim(Arr::get($post, 'location'));
            $lat=trim(Arr::get($post, 'lat'));
            $lng=trim(Arr::get($post, 'lng'));

            $build  = new App_Activity_Build;

            if ($activityId > 0)
            {
                $build->updateBasic($activityId, $uid, $country, $city,$cityId, $locName, $srv70s, $srv80s, $srv90s, $srv00s, $srvMin, $srvMax, $lat, $lng);
                $tid = $activityId;
            }
            else
            {
                $tid    = $build->createByBasic($uid, $country, $city,$cityId, $locName, $srv70s, $srv80s, $srv90s, $srv00s, $srvMin, $srvMax, $lat, $lng);
            }

            if ($tid > 0)
                $this->request->redirect('/activity/create_days/'.$tid);
            else
                $this->request->redirect('/activity/create_basic');
        }
    }

    public function action_create_days($activityId)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $this->template->set('step', 'days');
            $this->template->set_filename('smarty:www/activity/create');

            $activity = new App_Activity($activityId);
            $detail   = $activity->detail();

            $this->template->set('activity', $detail);
        }
        else
        {
            $name    = trim(Arr::get($post, 'name'));
            $summary = trim(Arr::get($post, 'summary'));
            $todolist= trim(Arr::get($post, 'todolist'));
            $hours   = (int) Arr::get($post, 'hours');
            
            list($thumbUrl, $thumbPos)   = Media::save_upload_file('thumb', Kohana::config('env.image.activity_thumb'));
            list($bannerUrl, $bannerPos) = Media::save_upload_file('bannerUrl', Kohana::config('env.image.activity_banner'));
            //批量上传图片
            $imgs=array();
            $file_arr=array();
            if($_FILES['images']){
            	$cou=count($_FILES['images']['name']);
            	for($i = 0; $i < $cou ;$i++){
            		if($_FILES['images']['name'][$i]){
            			$file_arr[$i]['name'] = $_FILES['images']['name'][$i];
            			$file_arr[$i]['type'] = $_FILES['images']['type'][$i];
            			$file_arr[$i]['tmp_name'] = $_FILES['images']['tmp_name'][$i];
            			$file_arr[$i]['error'] = $_FILES['images']['error'][$i];
            			$file_arr[$i]['size'] = $_FILES['images']['size'][$i];
            		}
            	}
            }
            if(!empty($file_arr)){
            	foreach($file_arr as $k => $v) {
            		$_FILES['images'] = $v;
            		list($imgUrl, $imgPos) = Media::save_upload_file('images', Kohana::config('env.image.activity_images'));
            		if(!empty($imgUrl)){
            			$imgs[]=trim($imgUrl);
            		}
            	}
            }
            //融合新上传的图片和之前的图片
            $imgsLast=Arr::get($post, 'ImgsLastTime',array());
            //去除空值
            foreach ($imgsLast as $k=>$v){
            	if(empty($v)){
            		unset($imgsLast[$k]);
            	}
            }
            if(!empty($imgsLast)){
            	$imgs=array_merge($imgs,$imgsLast);
            }

            $build   = new App_Activity_Build;
            if ($build->updateDays($activityId, $name, $summary, $todolist, $hours, $thumbUrl, $bannerUrl, $imgs))
            {
                $this->request->redirect('/activity/create_times/'.$activityId);
            }
            else
            {
                $this->request->redirect('/activity/create_days/'.$activityId);
            }
        }
    }
    
    private function delNull($v){
    	if (empty($v))
    	{
    		return false;
    	}
    	return true;
    }

    public function action_create_price ($activityId)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $activity = new App_Activity($activityId);
            $this->template->set('activity', $activity->detail());
            $this->template->set('step', 'price');
            $this->template->set_filename('smarty:www/activity/create');
        }
        else
        {
            $uid    = $this->_uid;
            $priceService = Arr::get($post, 'priceService');
            $descService  = trim(Arr::get($post, 'descService'));
  
            $build  = new App_Activity_Build;
            if ($build->updatePrice($activityId, $priceService, $descService))
            {
                $this->request->redirect('/activity/create_bank/'.$activityId);
            }
            else
            {
                $this->request->redirect('/activity/create_price/'.$activityId);
            }
        }
 
    }

    public function action_create_times ($activityId)
    {
        $post = $this->_post;
        if (empty($post))
        {
            
            $activity = new App_Activity($activityId);
            $this->template->set('activity', $activity->detail());

            $this->template->set('step', 'times');
            $this->template->set_filename('smarty:www/activity/create');
        }
        else
        {
            $startDay = trim(Arr::get($post, 'startDay'));
            $stopDay  = trim(Arr::get($post, 'stopDay'));
            $freeDays = trim(Arr::get($post, 'freeTimeDays'));

            $build  = new App_Activity_Build;
            if ($build->updateTimes($activityId, $startDay, $stopDay, $freeDays))
            {
                $this->request->redirect('/activity/create_price/'.$activityId);
            }
            else
            {
                $this->request->redirect('/activity/create_times/'.$activityId);
            }
        }
 
    }

    public function action_create_bank ($activityId)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $activity = new App_Activity($activityId);
            $adetail= $activity->detail();
            $bank = new UserExt_BanK($this->_uid);
            $blist=$bank->getBankList();
            $accountdf=array();
            $bchoosen=array();
            if(!empty($adetail['accountUserName'])){
               $bchoosen['accountUserName']=$adetail['accountUserName'];
               $bchoosen['accountType']=$adetail['accountType'];
               $bchoosen['accountName']=$adetail['accountName'];
               foreach($blist as &$val)
               {
                    if($val['accountUserName']==$adetail['accountUserName'])
                    {$val=array();}
               }
               unset($val);
            }else{
                foreach($blist as &$val)
                {
                        if($val['isDefault'])
                        {$accountdf=$val;$val=array();}
                }
               unset($val);
            }
            $this->template->set('activity', $adetail);
            $this->template->set('bankchoosen', $bchoosen);
            $this->template->set('accountdf', $accountdf);
            $this->template->set('bankList', $blist);
            $this->template->set('step', 'bank');
            $this->template->set_filename('smarty:www/activity/create');
        }
        else
        {
            $accountType     = trim(Arr::get($post, 'accountType'));
            $accountName     = trim(Arr::get($post, 'accountName'));
            $accountUserName = trim(Arr::get($post, 'accountUserName'));

            $build  = new App_Activity_Build;
            if ($build->updateBank($activityId, $accountType, $accountName, $accountUserName))
            {
                $this->request->redirect('/activity/create_succ/'.$activityId);
            }
            else
            {
                $this->request->redirect('/activity/create_bank/'.$activityId);
            }
        }
    }

    // 发布路线成功
    public function action_create_succ ($activityId)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $activity = new App_Activity($activityId);
            $popularize = new Popularize;

            $this->template->set('step', 'succ');
            $this->template->set('activity', $activity->detail());
            $this->template->set('canRequestSubmittedPrize', $activity->canRequestSubmittedPrize($this->_uid));
            $this->template->set('inviteCode', $popularize->getInviteCode($this->_uid));
            $this->template->set_filename('smarty:www/activity/create');
        }
    }
}
